<?php

namespace App\Http\Controllers;

use App\Libs\SmsCode;
use Illuminate\Http\Request;
use App\Libs\Ucpaas;
use App\Models\User;

class SmsController extends Controller
{
    public function sendCode(Request $request)
    {

        $mobile = $request->mobile;

        if (\Cache::has($mobile . '-' . $request->getClientIp())) {
            fail('发送频率超过限制');
        }

        if (!Verify_Phone($mobile)) {
            fail('手机号格式不正确');
        }

        //登录发送验证码验证手机是否存在
        if ($request->getRequestUri() == '/api/sms/code_login') {
            $exists = User::where('mobile', $mobile)->exists();
            if (!$exists) {
                fail('信息不存在');
            }
        }

        $ucpass = new Ucpaas([
            'accountsid' => config('sms.sid'),
            'token' => config('sms.token')
        ]);

        $code = random_int(1000, 9999);
        //$code = 1234;
        $param = "{$code},60";

        //70字内（含70字）计一条，超过70字，按67字/条计费，超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
        $json = $ucpass->SendSms(config('sms.appid'), '609999', $param, $mobile);

        $result = json_decode($json);
        if ($result->code === '000000') {
            \Cache::put($mobile, $code, 60);
            \Cache::put($mobile . '-' . $request->getClientIp(), 1, 30);
        }

        return success($result);
    }

    public function bindMobile(Request $request)
    {
        $request->validate([
            'mobile' => 'required',
            'code' => 'required',
        ]);

        $mobile = $request->mobile;
        SmsCode::check($mobile, $request->code);

        $exists = User::where('mobile', $mobile)->exists();
        if ($exists) {
            fail('手机号已绑定');
        }
        auth()->user()->update([
            'mobile' => $mobile,
            'username' => $mobile
        ]);
        return success('ok');
    }
}
